<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper" style="margin-bottom:16px">
      <a-row style="margin-bottom:16px">
        <a-col :md="8" :sm="24">
          <a-input-search @search="search" enterButton="查询" />
        </a-col>
      </a-row>
      <a-row>
        <a-button type="primary" class="actionButton" @click="add">添加</a-button>
        <a-popconfirm v-if="isAdmin()" title="确定删除?" okText="确定" cancelText="取消" @confirm="del">
          <a-button type="primary" class="actionButton">删除</a-button>
        </a-popconfirm>
      </a-row>
    </div>
    <a-card :body-style="{ padding: 0 }" :bordered="false">
      <a-spin :spinning="spinning" tip="获取数据中...">
        <div class="spin-content">
          <a-table size="small" bordered :rowKey="record => record.ID" :columns="columns" :dataSource="data" :pagination="pagination" :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :rowClassName="setRowClassName">
            <span slot="action" slot-scope="text, record">
              <template>
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>修改</span>
                  </template>
                  <a-button size="small" type="link" @click="handleEdit(record)">修改</a-button>
                </a-tooltip>
                <a-divider type="vertical" />
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>查看</span>
                  </template>
                  <a-button size="small" type="link" @click="handleView(record)">查看字典</a-button>
                </a-tooltip>
                <!-- <a-popconfirm title="确定删除?" okText="确定" cancelText="取消" @confirm="handleDelete(record)">
                <a-button type="primary" shape="circle" icon="delete"></a-button>
                </a-popconfirm>-->
              </template>
            </span>
          </a-table>
        </div>
      </a-spin>
      <!-- <a-pagination size="small" showQuickJumper :defaultCurrent="2" :total="500" @change="onChange" /> -->
    </a-card>
    <a-modal :title="title" :visible="visible" :centered="true" @cancel="handleCancel" :footer="null">
      <div class="waterArea" style="background-color:#fff">
        <a-spin :spinning="loadingItemI">
          <a-form :form="form">
            <a-form-item v-bind="formItemLayout" label="字典类型">
              <a-input v-decorator="['Title', { rules: [{ required: true, message: '请填写字典类型!' }] }]" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="字典类型编号">
              <a-input v-decorator="['Code', { rules: [{ required: true, message: '请填写字典类型编号!' }] }]" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="备注">
              <a-input v-decorator="['Remark']" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout1" style="text-align:center;margin-bottom:0">
              <a-button type="primary" @click="ok">确定</a-button>
            </a-form-item>
          </a-form>
        </a-spin>
      </div>
    </a-modal>

    <a-modal :title="titleItemI" :visible="visibleItemI" :centered="true" @cancel="handleCancelItemI" :footer="null">
      <div class="waterArea" style="background-color:#fff">
        <a-spin :spinning="loadingItemI">
          <a-form :form="formItemI">
            <a-form-item v-bind="formItemLayout" label="字典名称">
              <a-input v-decorator="['Title', { rules: [{ required: true, message: '请填写角色名称!' }] }]" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="字典编号">
              <a-input v-decorator="['Code']" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="上级字典" v-if="hasParentId">
              <a-select style="width:100%" allowClear v-decorator="['ParentId']">
                <a-select-option v-for="(item, index) in dictDrop" :key="item.ID" :value="item.ID">
                  {{ item.Title }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="排序">
              <a-input-number v-decorator="['Sortnum', { rules: [{ required: true, message: '请填写排序!' }] }]" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="备注">
              <a-input v-decorator="['Remark']" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout1" style="text-align:center;margin-bottom:0">
              <a-button type="primary" @click="okItemI">确定</a-button>
            </a-form-item>
          </a-form>
        </a-spin>
      </div>
    </a-modal>
    <a-modal :title="titleItem" :width="800" :visible="visibleItem" :centered="true" @cancel="handleCancelItem" :footer="null">
      <div class="waterArea" style="background-color:#fff">
        <a-row style="margin-bottom:8px;margin-top:8px">
          <a-button type="primary" class="actionButton" @click="addItem">添加</a-button>
          <a-popconfirm v-if="isAdmin()" title="确定删除?" okText="确定" cancelText="取消" @confirm="delItem">
            <a-button type="primary" class="actionButton">删除</a-button>
          </a-popconfirm>
        </a-row>
        <a-spin :spinning="spinningItem" tip="获取数据中...">
          <div class="spin-content">
            <a-table size="small" bordered :rowKey="record => record.ID" :columns="columnsItem" :dataSource="dataItem" :rowSelection="{ selectedRowKeys: selectedRowKeysItem, onChange: onSelectChangeItem }">
              <a-icon slot="expandIcon" slot-scope="props" :type="[props.expanded ? 'down' : 'up']" />
              <span slot="action" slot-scope="text, record">
                <template>
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>修改</span>
                    </template>
                    <a-button type="link" @click="handleEditItem(record)">修改</a-button>
                  </a-tooltip>
                  <!-- <a-popconfirm title="确定删除?" okText="确定" cancelText="取消" @confirm="handleDelete(record)">
                <a-button type="primary" shape="circle" icon="delete"></a-button>
                </a-popconfirm>-->
                </template>
              </span>
            </a-table>
          </div>
        </a-spin>
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import { getDictById, getDicList, getDicDropList, saveDict, deleteDict, getDictCategoryList, getDictCategoryById, saveDictCategory, deleteDictCategory } from '@/api/dict'
import moment from 'moment'
import { authDevice } from '@/utils/mixin'
const newLocal = this
export default {
  mixins: [authDevice],
  data() {
    return {
      action: 'add',
      title: '',
      titleItem: '',
      titleItemI: '',
      tableCardLoad: false,
      spinning: false,
      spinningItem: false,
      hasParentId: false,
      data: [],
      dataItem: [],
      queryParam: {},
      pagination: {
        onChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize)
        },
        current: 1,
        total: 0,
        showQuickJumper: true,
        size: 'small',
        defaultPageSize: 10,
        showTotal: total => `共 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],
        onShowSizeChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize)
        },
        position: 'top'
      },
      // 表头
      columnsItem: [
        {
          title: '字典名称',
          dataIndex: 'Title',
          key: 'Title',
          width: 400
        },
        {
          title: '排序',
          dataIndex: 'Sortnum',
          key: 'Sortnum',
          align: 'center'
        },
        {
          title: '所属分类',
          dataIndex: 'DictCategoryTitle',
          key: 'DictCategoryTitle',
          align: 'center'
        },
        {
          title: '操作',
          width: 100,
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      // 表头
      columns: [
        {
          title: '字典类型',
          dataIndex: 'Title',
          key: 'Title',
          align: 'center'
        },
        {
          title: '字典类型编号',
          dataIndex: 'Code',
          key: 'Code',
          align: 'center'
        },
        {
          title: '操作',
          width: 200,
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      selectedRowKeys: [],
      selectedRowKeysItem: [],
      visible: false,
      visibleItem: false,
      visibleItemI: false,
      loading: false,
      loadingItemI: false,
      form: this.$form.createForm(this),
      formItemI: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 }
        }
      },
      formItemLayout1: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 0 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        }
      },
      dictDrop: [],
      currentId: null,
      currentItemId: null
    }
  },
  created() {
    var _this = this
    _this.spinning = true
    _this.initData(_this.queryParam)
  },
  methods: {
    ok() {
      const {
        form: { validateFields }
      } = this
      validateFields((errors, values) => {
        if (!errors) {
          this.loading = true
          setTimeout(() => {
            const value = {
              ...values,
              ID: this.currentId
            }
            saveDictCategory(value).then(res => {
              this.currentId = null
              this.initData(this.queryParam)
              this.loading = false
              this.visible = false
            })
          }, 1000)
        } else {
        }
      })
    },
    okItem() {},
    okItemI() {
      const {
        formItemI: { validateFields }
      } = this
      validateFields((errors, values) => {
        if (!errors) {
          this.loadingItemI = true
          setTimeout(() => {
            const value = {
              ...values,
              ParentId: values['ParentId'] == undefined ? null : values['ParentId'],
              CategoryId: this.currentId,
              ID: this.currentItemId
            }
            saveDict(value).then(res => {
              this.initDataItem(this.currentId)
              this.currentItemId = null
              this.loadingItemI = false
              this.visibleItemI = false
            })
          }, 1000)
        } else {
        }
      })
    },
    initData(data) {
      var _this = this
      _this.spinning = true
      getDictCategoryList(data)
        .then(res => {
          // if (res.success) {
          _this.data = res
          // _this.pagination.total = res.page.RecordCount
          // } else {
          //   this.$message.error(res.message)
          // }
        })
        .finally(() => {
          this.spinning = false
        })
    },
    generateDataItem(dataItem) {
      dataItem.forEach(item => {
        if (item.hasOwnProperty('Childrens')) {
          if (item.Childrens.length == 0) {
            delete item.Childrens
          } else {
            item.children = item.Childrens
            return this.generateDataItem(item.Childrens)
          }
        }
      })
    },
    initDataItem(data) {
      this.spinningItem = true
      getDicList({ categoryId: data })
        .then(res => {
          this.dataItem = res.filter(a => a.ID !== -1)
          this.generateDataItem(this.dataItem)
        })
        .finally(() => {
          this.spinningItem = false
        })
      getDicDropList({ CategoryId: data }).then(res => {
        this.dictDrop = res.data
      })
    },
    handleCancel() {
      this.visible = false
    },
    handleCancelItemI() {
      this.visibleItemI = false
    },
    handleCancelItem() {
      this.visibleItem = false
    },
    search(data) {
      var _this = this
      _this.spinning = true
      _this.queryParam = Object.assign({}, _this.queryParam, { index: 1 })
      this.pagination.current = 1
      _this.initData(_this.queryParam)
    },
    add() {
      this.title = '添加字典类型'
      this.action = 'add'
      this.visible = true
      newLocal.currentId = null
      this.form.resetFields()
    },
    addItem() {
      Object.assign(this, {
        visibleItemI: true,
        titleItemI: '添加字典',
        hasParentId: true,
        currentItemId: null
      })

      this.formItemI.resetFields()
    },

    pageOnChange(index, pageSize) {
      this.tableCardLoad = true
      Object.assign(this.pagination, {
        current: index,
        pageSize,
        index
      })
      Object.assign(this.queryParam, {
        pageSize,
        index
      })
      this.initData(this.queryParam)
    },
    handleEdit(data) {
      this.spinning = true
      this.action = 'edit'
      this.title = '修改字典类型'
      getDictCategoryById({ dictCategoryId: data.ID })
        .then(res => {
          this.visible = true
          this.loading = true
          setTimeout(() => {
            this.currentId = data.ID
            this.form.setFieldsValue({ Title: data.Title })
            this.form.setFieldsValue({ Code: data.Code })
            this.form.setFieldsValue({ Remark: data.Remark })
          }, 500)
        })
        .finally(() => {
          this.loading = false
          this.spinning = false
        })
    },
    handleEditItem(data) {
      this.spinningItem = true
      this.hasParentId = data.ParentId != null
      this.titleItemI = '修改字典'
      getDictById({ dictId: data.ID })
        .then(res => {
          this.visibleItemI = true
          this.loadingItemI = true
          setTimeout(() => {
            this.currentItemId = data.ID
            this.formItemI.setFieldsValue({ Title: data.Title })
            this.formItemI.setFieldsValue({ Code: data.Code })
            this.formItemI.setFieldsValue({ ParentId: data.ParentId })
            this.formItemI.setFieldsValue({ Sortnum: data.Sortnum })
            this.formItemI.setFieldsValue({ Remark: data.Remark })
          }, 500)
        })
        .finally(() => {
          this.loadingItemI = false
          this.spinningItem = false
        })
    },
    handleView(data) {
      this.titleItem = '查看字典'
      this.visibleItem = true
      this.currentId = data.ID
      this.initDataItem(data.ID)
    },
    del() {
      this.spinning = true
      deleteDictCategory(this.selectedRowKeys)
        .then(res => {
          this.initData(this.queryParam)
          this.selectedRowKeys = []
        })
        .finally(() => {
          this.spinning = false
        })
    },
    delItem() {
      this.spinningItem = true
      deleteDict(this.selectedRowKeysItem)
        .then(res => {
          this.initDataItem(this.currentId)
        })
        .finally(() => {
          this.spinningItem = false
        })
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    onSelectChangeItem(selectedRowKeys) {
      this.selectedRowKeysItem = selectedRowKeys
    },
    handleDownload(data) {
      this.spinning = true
      exportWord({ id: data.ID })
        .then(res => {
          const a = returnXls(res)
          window.open(a)
        })
        .finally(() => {
          this.spinning = false
        })
    },
    expandIcon(props) {
      // console.log(props);
      if (props.record.fileInfoList.length > 0) {
        if (props.expanded) {
          //有数据-展开时候图标
          return (
            <a
              style="color: 'black',margin-right:0px"
              onClick={e => {
                props.onExpand(props.record, e)
              }}
            >
              <a-icon type="down" />{' '}
            </a>
          )
        } else {
          //有数据-未展开时候图标
          return (
            <a
              style="color: 'black' ,margin-right:0px"
              onClick={e => {
                props.onExpand(props.record, e)
              }}
            >
              <a-icon type="right" />
            </a>
          )
        }
      } else {
        //无数据-图标
        return (
          <span style="margin-right:0px">
            <a-icon type="smile" />
          </span>
        )
      }
    },
    generateData(data, res) {
      data = this.pushData(data, res)
    },
    setRowClassName(record, idx) {
      return idx % 2 == 1 ? 'bg-row' : ''
    }
  }
}
</script>

<style lang="less" scoped>
.actionButton {
  margin-left: 10px;
}
</style>
